package cn.otrue.patienthealthmanager.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.DoctorChatActivity;
import cn.otrue.patienthealthmanager.activity.QuestionnaireDetailActivity;
import cn.otrue.patienthealthmanager.bean.DoctorBaseinfo;
import cn.otrue.patienthealthmanager.bean.MessageCenterModel;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.db.DBTools;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.xmpp.XmppTool;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

public class CenterMessageAdapter extends BaseAdapter {
	List<MessageCenterModel> mapMessageData;
	LayoutInflater inflater;
	Context context;
	private AlertDialog alertDialog;
	private TextView tv_centermessage_datatips;
	private Handler adapterHandler;
	private boolean isFreeAsk;// 用于判断是否是免费问的弹窗
	private DbUtils db = DBTools.db;

	public CenterMessageAdapter(List<MessageCenterModel> mapMessageData,
			Context context, Handler adapterHandler) {
		this.mapMessageData = mapMessageData;
		inflater = LayoutInflater.from(context);
		this.context = context;
		this.adapterHandler = adapterHandler;
	}

	@Override
	public int getCount() {
		return mapMessageData != null ? mapMessageData.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return mapMessageData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	private String from;
	private ServerHandler messageHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {
				if (isFreeAsk == true) {
					Intent logIntent = new Intent(context,
							DoctorChatActivity.class);
					logIntent.putExtra("from", from);
					context.startActivity(logIntent);
				}
				Toast.makeText(context, "服务器同意成功", 0).show();
				adapterHandler.sendEmptyMessage(99);
			} else {
				Toast.makeText(context, "服务器同意失败", 0).show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			super.onFail(data, state);
		}
	};
	private TextView tv_catt;

	@SuppressLint("SimpleDateFormat")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		HolderView holder;
		if (convertView == null) {
			holder = new HolderView();
			convertView = inflater.inflate(R.layout.layout_centermessage_item,
					null);
			holder.iv_center_message_item = (ImageView) convertView
					.findViewById(R.id.iv_center_message_item);
			holder.tv_centermessage_title = (TextView) convertView
					.findViewById(R.id.tv_centermessage_title);
			holder.tv_centermessage_describe = (TextView) convertView
					.findViewById(R.id.tv_centermessage_describe);
			holder.tv_centermessage_time = (TextView) convertView
					.findViewById(R.id.tv_centermessage_time);
			convertView.setTag(holder);
		} else {
			holder = (HolderView) convertView.getTag();
		}

		final MessageCenterModel messageInfo = mapMessageData.get(position);

		holder.tv_centermessage_title.setText(messageInfo.getTitle());
		String time = messageInfo.getCreatetime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-d H:m:s");
		try {
			Date date = format.parse(time);
			time = format.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
			time = "";
		}
		holder.tv_centermessage_time.setText(time);
		if ((messageInfo.getTypeid() != null)
				&& !("".equals(messageInfo.getTypeid()))) {
			switch (messageInfo.getTypeid()) {
			case MyConst.TYPEID_P_attention_D:
				// 患者关注医生申请
				holder.iv_center_message_item
						.setImageResource(R.drawable.huanzheguanzhuyisheng);
				holder.tv_centermessage_title.setText("您请求添加"
						+ CommonUtil.getName(messageInfo.receivername,
								messageInfo.receivername,
								messageInfo.getReceiver()) + "为好友");
				break;
			case MyConst.TYPEID_D_respond_P:
				// 患者回应关注
				holder.iv_center_message_item
						.setImageResource(R.drawable.d_guanzhu_p);
				holder.tv_centermessage_title.setText("您回应了"
						+ CommonUtil.getName(messageInfo.receivername,
								messageInfo.receivername,
								messageInfo.getReceiver()) + "的邀请");
				break;
			case MyConst.TYPEID_questionnaire:
				// 问卷调整
				holder.iv_center_message_item
						.setImageResource(R.drawable.wenjuan);
				holder.tv_centermessage_title.setText(CommonUtil.getName(
						messageInfo.sendername, messageInfo.sendername,
						messageInfo.getSender())
						+ "向您发送了问卷调查");
				break;
			case MyConst.TYPEID_D_invite_P:
				// 医生邀请患者关注
				holder.iv_center_message_item
						.setImageResource(R.drawable.yishengyaoqinghuanzheguanzhu);
				holder.tv_centermessage_title.setText(CommonUtil.getName(
						messageInfo.sendername, messageInfo.sendername,
						messageInfo.getSender())
						+ "医生邀请您的关注");
				break;
			case MyConst.TYPEID_SYSTEM:
				// 系统消息
				holder.iv_center_message_item
						.setImageResource(R.drawable.xitong);
				holder.tv_centermessage_title.setText("系统消息");
				break;
			default:
				break;
			}
		}
		if (MyConst.ISLOOK_SURE == messageInfo.getIsLooked()) {
			holder.tv_centermessage_describe.setText("已查看");
		}
		if (MyConst.ISDETAIL_SURE == messageInfo.getDealResult()) {
			holder.tv_centermessage_describe.setText("已同意");
		}
		if (MyConst.ISDETAIL_NO == messageInfo.getDealResult()) {
			holder.tv_centermessage_describe.setText("已拒绝");
		}
		convertView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if ((messageInfo.getTypeid() != null)
						&& !("".equals(messageInfo.getTypeid()))) {
					switch (messageInfo.getTypeid()) {
					case MyConst.TYPEID_D_invite_P:
						// 医生邀请患者关注
						// if (mapMessageData.get(position).getIsDeal() == 0) {
						// isFreeAsk = false;
						// setIsLook(position);
						// initDataInputDialog(messageInfo.getContent(),
						// position);
						// }
						break;
					case MyConst.TYPEID_questionnaire:
						setIsLook(position);
						Intent questionIntent = new Intent(context,
								QuestionnaireDetailActivity.class);
						questionIntent.putExtra("researchId",
								mapMessageData.get(position).businessID);
						context.startActivity(questionIntent);
						break;
					case MyConst.FREE_REPLY:
						if (mapMessageData.get(position).getIsDeal() == 0) {

							setIsLook(position);
							isFreeAsk = true;
							from = mapMessageData.get(position).getSender_jid();
							initDataInputDialog(messageInfo.getContent(),
									position);
							try {
								DoctorBaseinfo doctorInfo = db
										.findFirst(Selector.from(
												DoctorBaseinfo.class).where(
												"aliasAccount",
												"=",
												mapMessageData.get(position)
														.getSender()));
								if (doctorInfo != null) {
									doctorInfo.setNickname(mapMessageData.get(
											position).getSendername());
									doctorInfo.setAliasAccount(mapMessageData
											.get(position).getSender());
									doctorInfo.setHeadimg(mapMessageData.get(
											position).getDoctorsFace());
									db.update(doctorInfo);
								} else {
									DoctorBaseinfo newDoctor = new DoctorBaseinfo();
									newDoctor.setNickname(mapMessageData.get(
											position).getSendername());
									newDoctor.setAliasAccount(mapMessageData
											.get(position).getSender());
									newDoctor.setHeadimg(mapMessageData.get(
											position).getDoctorsFace());
									db.save(newDoctor);

								}
							} catch (DbException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						break;
					default:
						break;
					}
				}
			}
		});
		return convertView;
	}

	public void setIsLook(int position) {
		if (mapMessageData.get(position).getIsLooked() == 0) {
			HashMap<String, Object> map1 = new HashMap<String, Object>();
			map1.put("seq", mapMessageData.get(position).getSeq());
			TransferParameter parameter1 = new TransferParameter();
			parameter1.setData(map1);
			new HttpServer().post(HttpCons.IFMODIFYTHEVIEW, parameter1,
					messageHandler); // 添加互相关注
		}
	}

	public void initDataInputDialog(String content, final int position) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		View view = inflater.inflate(R.layout.dialog_attention_patinent_op,
				null);
		TextView tv_catt = (TextView) view.findViewById(R.id.tv_catt);
		TextView tv_catt_datatips = (TextView) view
				.findViewById(R.id.tv_catt_datatips);
		switch (mapMessageData.get(position).getTypeid()) {

		case MyConst.TYPEID_D_invite_P:
			// 医生邀请患者关注
			tv_catt_datatips.setText("您是否接受医生邀请！");
			break;
		case MyConst.FREE_REPLY:
			tv_catt_datatips.setText("您的询问已回复，是否继续去询问！");
			break;
		default:
			break;
		}

		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				alertDialog.dismiss();
			}
		});
		tv_catt_dialogLeft.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Roster roster;
				try {
					roster = XmppTool.getConnection().getRoster();
					if (XmppTool.addUser(roster, mapMessageData.get(position)
							.getSender_jid(), mapMessageData.get(position)
							.getSender(), "Friends")) {
						Toast.makeText(context, "open同意成功", 0).show();
						HashMap<String, Object> map1 = new HashMap<String, Object>();
						map1.put("state", "1");
						map1.put("sender", mapMessageData.get(position)
								.getReceiver());
						map1.put("receiver", mapMessageData.get(position)
								.getSender());
						map1.put("isDeal", "1");
						map1.put("dealResult", "1");
						String typeid = mapMessageData.get(position)
								.getTypeid() + "";
						typeid = typeid;
						map1.put("typeid", "101");
						// String seq=""+;
						// seq=seq;
						map1.put("seq", mapMessageData.get(position).getSeq());
						TransferParameter parameter1 = new TransferParameter();
						parameter1.setUsername(MyConst.getACCOUNT());
						parameter1.setPagesize("");
						parameter1.setCurrentPage("");
						parameter1.setData(map1);
						new HttpServer().post(
								HttpCons.UPDATE_DOCTOR_ATTENTIONINFO,
								parameter1, messageHandler); // 添加互相关注
						alertDialog.dismiss();
					} else {
						Toast.makeText(context, "open同意失败", 0).show();
						alertDialog.dismiss();
					}
				} catch (XMPPException e) {
					Log.e("XMPP", "添加好友->连接异常");
				}
			}
		});
		tv_catt_dialogRight.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("state", "1");
				map.put("sender", mapMessageData.get(position).getReceiver());
				map.put("receiver", mapMessageData.get(position).getSender());
				map.put("isDeal", "1");
				map.put("dealResult", "2");
				// String typeid=mapMessageData.get(position).getTypeid()+"";
				// typeid=typeid;
				map.put("typeid", "101");
				map.put("seq", mapMessageData.get(position).getSeq());
				TransferParameter parameter = new TransferParameter();
				parameter.setUsername(MyConst.getACCOUNT());
				parameter.setPagesize("");
				parameter.setCurrentPage("");
				parameter.setData(map);
				new HttpServer().post(HttpCons.UPDATE_DOCTOR_ATTENTIONINFO,
						parameter, messageHandler); // 添加互相关注
				alertDialog.dismiss();
			}
		});
		builder.setView(view);
		alertDialog = builder.create();
		alertDialog.show();
	}

	/*
	 * private View initDataInputDialog(int addType, DataDialogListener
	 * dataListener, String messageCenterSeq) {
	 * 
	 * TextView tv_catt_noticeTile = (TextView) view
	 * .findViewById(R.id.tv_catt_noticeTile); tv_catt = (TextView)
	 * view.findViewById(R.id.tv_catt); tv_catt.setOnClickListener(new
	 * OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { alertDialog.dismiss(); } });
	 * tv_otrue_dialogLeft = (TextView) view
	 * .findViewById(R.id.tv_catt_dialogLeft);
	 * tv_otrue_dialogLeft.setOnClickListener(dataListener);
	 * tv_otrue_dialogRight = (TextView) view
	 * .findViewById(R.id.tv_catt_dialogRight);
	 * tv_otrue_dialogRight.setOnClickListener(dataListener); et_otrue_data =
	 * (EditText) view.findViewById(R.id.et_catt_data);
	 * tv_centermessage_datatips = (TextView) view
	 * .findViewById(R.id.tv_catt_datatips);
	 * 
	 * dataListener.setAddType(addType, 0); switch (addType) { case 1:
	 * tv_catt_noticeTile.setText("关注医生"); break; default: break; }
	 * 
	 * HashMap<String, Object> map = new HashMap<String, Object>();
	 * map.put("seq", messageCenterSeq);
	 * 
	 * TransferParameter parameter = new TransferParameter();
	 * parameter.setUsername(MyConst.ACCOUNT); parameter.setPagesize("10");
	 * parameter.setCurrentPage("1");
	 * 
	 * parameter.setData(map); new
	 * HttpServer().post(HttpCons.QUERYMESSAGECENTERDETAIL, parameter,
	 * messageHandler);
	 * 
	 * return view;
	 * 
	 * }
	 */

	/*
	 * public class DataDialogListener implements OnClickListener { private int
	 * addType; private int id;
	 * 
	 * public void setAddType(int addType, int id) { this.id = id; this.addType
	 * = addType; }
	 * 
	 * @Override public void onClick(View v) {
	 * 
	 * switch (v.getId()) { case R.id.tv_catt: alertDialog.dismiss(); break;
	 * case R.id.tv_catt_dialogRight:// 取消
	 * 
	 * HashMap<String, Object> map = new HashMap<String, Object>();
	 * map.put("state", "1"); map.put("sender", sender); map.put("receiver",
	 * receiver); map.put("isDeal", "0"); map.put("seq", Seq); TransferParameter
	 * parameter = new TransferParameter();
	 * parameter.setUsername(MyConst.ACCOUNT); parameter.setPagesize("");
	 * parameter.setCurrentPage("");
	 * 
	 * parameter.setData(map);
	 * 
	 * new HttpServer().post(HttpCons.UPDATE_DOCTOR_ATTENTIONINFO, parameter,
	 * messageHandler); // 添加互相关注 break; case R.id.tv_catt_dialogLeft:// 确定
	 * 
	 * Roster roster; try { roster = XmppTool.getConnection().getRoster(); if
	 * (addUser(roster, sender_jid, sender, "Friends")) {
	 * Toast.makeText(context, "open同意成功", 0).show(); HashMap<String, Object>
	 * map1 = new HashMap<String, Object>(); map1.put("state", "1");
	 * map1.put("sender", sender); map1.put("receiver", receiver);
	 * map1.put("isDeal", "1");
	 * 
	 * map1.put("seq", Seq); TransferParameter parameter1 = new
	 * TransferParameter(); parameter1.setUsername(MyConst.ACCOUNT);
	 * parameter1.setPagesize(""); parameter1.setCurrentPage("");
	 * 
	 * parameter1.setData(map1);
	 * 
	 * new HttpServer().post( HttpCons.UPDATE_DOCTOR_ATTENTIONINFO, parameter1,
	 * messageHandler); // 添加互相关注
	 * 
	 * } else { Toast.makeText(context, "open同意失败", 0).show(); } } catch
	 * (XMPPException e) { Log.e("XMPP", "添加好友->连接异常"); }
	 * 
	 * break;
	 * 
	 * } } }
	 */

	public class HolderView {
		ImageView iv_center_message_item;
		TextView tv_centermessage_title;
		TextView tv_centermessage_describe;
		TextView tv_centermessage_time;
	}
}
